package com.yupi.springbootinit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.InterfaceSubmitMapper;
import com.yupi.springbootinit.model.dto.interfacesubmit.InterfaceSubmitAddRequest;
import com.yupi.springbootinit.model.dto.interfacesubmit.InterfaceSubmitQueryRequest;
import com.yupi.springbootinit.model.dto.interfacesubmit.InterfaceSubmitUpdateRequest;
import com.yupi.springbootinit.model.entity.InterfaceSubmit;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.InterfaceSubmitVO;
import com.yupi.springbootinit.service.InterfaceSubmitService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author Administrator
* @description 针对表【interface_submit(接口审核表)】的数据库操作Service实现
* @createDate 2025-04-17 13:19:04
*/
@Service
public class InterfaceSubmitServiceImpl extends ServiceImpl<InterfaceSubmitMapper, InterfaceSubmit>
    implements InterfaceSubmitService{


    /**
     * 根据id查询接口提审信息
     * @param id id
     * @return 接口提审信息
     */
    @Override
    public BaseResponse<InterfaceSubmit> getInterfaceSubmitDetail(Long id) {
        InterfaceSubmit interfaceSubmit = this.getById(id);
        if (ObjUtil.isEmpty(interfaceSubmit)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提审编号不存在");
        }
        return ResultUtils.success(interfaceSubmit);
    }

    /**
     * 分页查询接口提审信息(只返回自己的提审)
     *
     * @param queryRequest 查询条件
     * @param request
     * @return 接口提审分页结果
     */
    @Override
    public BaseResponse<Page<InterfaceSubmitVO>> getInterfaceSubmitVO(InterfaceSubmitQueryRequest queryRequest, HttpServletRequest request) {
        //每个用户查询自己的记录
        Object userLogin = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userLogin;
        InterfaceSubmit is = new InterfaceSubmit();
        BeanUtil.copyProperties(queryRequest, is);
        is.setCreateUserId(user.getId());
        //构建分页查询
        Page<InterfaceSubmit> interfaceSubmitPage = this.page(
                new Page<>(queryRequest.getCurrent(),
                queryRequest.getPageSize()),
                this.getQueryWrapper(is));
        //脱敏转换
        List<InterfaceSubmitVO> interfaceSubmitVOList = interfaceSubmitPage.getRecords().stream()
                .map((interfaceSubmit) -> {
                    InterfaceSubmitVO interfaceSubmitVO = new InterfaceSubmitVO();
                    BeanUtil.copyProperties(interfaceSubmit, interfaceSubmitVO);
                    return interfaceSubmitVO;
                })
                .collect(Collectors.toList());
        Page<InterfaceSubmitVO> interfaceSubmitVOPage = new Page<>(interfaceSubmitPage.getCurrent(), interfaceSubmitPage.getSize(), interfaceSubmitPage.getTotal());
        interfaceSubmitVOPage.setRecords(interfaceSubmitVOList);
        return ResultUtils.success(interfaceSubmitVOPage);
    }

    /**
     * 添加提审请求
     *
     * @param addRequest 请求信息
     * @param request
     * @return ok
     */
    @Override
    public BaseResponse<Boolean> addInterfaceSubmit(InterfaceSubmitAddRequest addRequest, HttpServletRequest request) {
        //获取登录信息
        Object userLogin = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userLogin == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请先登录");
        }
        User user = (User) userLogin;
        //添加请求
        InterfaceSubmit interfaceSubmit = new InterfaceSubmit();
        BeanUtil.copyProperties(addRequest, interfaceSubmit);
        //设置用户id
        interfaceSubmit.setCreateUserId(user.getId());
        //查询
        if (this.save(interfaceSubmit)){
            return ResultUtils.success(true);
        }
        throw new BusinessException(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 删除提审请求
     * @param id 审核请求id
     * @return ok
     */
    @Override
    public BaseResponse<Boolean> deleteInterfaceSubmit(Long id) {
        if (this.removeById(id)){
            return ResultUtils.success(true);
        }
        log.error("删除失败");
        throw new BusinessException(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 更新提审请求
     * @param updateRequest 请求信息
     * @return ok
     */
    @Override
    public BaseResponse<Boolean> updateInterfaceSubmit(InterfaceSubmitUpdateRequest updateRequest) {
        InterfaceSubmit interfaceSubmit = new InterfaceSubmit();
        BeanUtil.copyProperties(updateRequest, interfaceSubmit);
        if (this.updateById(interfaceSubmit)){
            return ResultUtils.success(true);
        }
        log.error("更新失败");
        throw new BusinessException(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 查询提审请求
     * @param queryRequest 请求信息
     * @return 脱敏后信息
     */
    @Override
    public BaseResponse<Page<InterfaceSubmitVO>> listInterfaceSubmit(InterfaceSubmitQueryRequest queryRequest) {
        if (queryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceSubmit interfaceSubmit = new InterfaceSubmit();
        BeanUtil.copyProperties(queryRequest, interfaceSubmit);
        //查询
        Page<InterfaceSubmit> page = this.page(
                new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize()),
                getQueryWrapper(interfaceSubmit)
        );
        //脱敏
        List<InterfaceSubmit> records = page.getRecords();
        List<InterfaceSubmitVO> interfaceSubmitVOList = records.stream().map(i -> {
            InterfaceSubmitVO iVO = new InterfaceSubmitVO();
            BeanUtil.copyProperties(i, iVO);
            return iVO;
        }).collect(Collectors.toList());
        //封装
        Page<InterfaceSubmitVO> interfaceSubmitVOPage = new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize(),page.getTotal());
        interfaceSubmitVOPage.setRecords(interfaceSubmitVOList);
        return ResultUtils.success(interfaceSubmitVOPage);
    }



    /**
     * 构建查询条件
     * @param queryRequest 请求信息
     * @return 查询条件
     */
    private QueryWrapper<InterfaceSubmit> getQueryWrapper(InterfaceSubmit queryRequest){
        QueryWrapper<InterfaceSubmit> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null){
            return queryWrapper;
        }
        Long id = queryRequest.getId();
        String interfaceName = queryRequest.getInterfaceName();
        String description = queryRequest.getDescription();
        String url = queryRequest.getUrl();
        Long createUserId = queryRequest.getCreateUserId();
        Integer status = queryRequest.getStatus();
        String method = queryRequest.getMethod();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(createUserId != null, "create_user_id", createUserId);
        queryWrapper.like(StrUtil.isNotBlank(interfaceName), "interface_name", interfaceName);
        queryWrapper.like(StrUtil.isNotBlank(description), "description", description);
        queryWrapper.like(StrUtil.isNotBlank(url), "url", url);
        queryWrapper.eq(status != null, "status", status);
        queryWrapper.eq(StrUtil.isNotBlank(method), "method", method);
        return queryWrapper;
    }

}




